package io.sundial.conversion.jackson;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.sundial.conversion.Converter;
import io.sundial.conversion.exception.DeserializeException;
import io.sundial.conversion.exception.SerializeException;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * Json转换器
 *
 * @author Payne 646742615@qq.com
 * 2018/12/25 15:40
 */
public class JsonConverter implements Converter {
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public String getContentType() {
        return "application/json";
    }

    @Override
    public byte[] serialize(Object obj) throws SerializeException {
        try (
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ) {
            objectMapper.writeValue(bos, obj);
            return bos.toByteArray();
        } catch (IOException e) {
            throw new SerializeException(e);
        }
    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> type) throws DeserializeException {
        try (
                ByteArrayInputStream bis = new ByteArrayInputStream(data)
        ) {
            return objectMapper.readValue(bis, type);
        } catch (IOException e) {
            throw new DeserializeException(e);
        }
    }

    public ObjectMapper getObjectMapper() {
        return objectMapper;
    }

    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }
}
